package com.coolcode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.coolcode.entity.LoginUserInfo;
import com.coolcode.entity.UserInfo;
import com.coolcode.mapper.MenuMapper;
import com.coolcode.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询用户信息
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserName, username);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

        if (Objects.isNull(userInfo)) {
            throw new RuntimeException("用户不存在");
//            throw new ValidationException(ExceptionErrorCode.LOGIN_FAIL, "用户不存在");
        }

        // 查询对应的权限信息
//        List<String> permissions = menuMapper.selectPermsByUserId(userInfo.getId());
        List<String> permissions = new ArrayList<>();
        return new LoginUserInfo(userInfo, permissions);
    }
}
